package pl.koziolekweb.szkola.KJChatUDP;

// KJ-ChatUDP/UDPSerwer.java
 
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.HashMap;

public class UDPSerwer {
    static final int PORT    = 54321;
    static final int BUFSIZE = 32*1024;
    static final HashMap<String,Integer> map =
                            new HashMap<String,Integer>();

    public static void main(String[] args) {
        DatagramSocket sock = null;
        DatagramPacket pack = null, rpac = null;

        try {
            sock = new DatagramSocket(PORT);
            pack = new DatagramPacket(
                    new byte[BUFSIZE],BUFSIZE);
            byte[] resp = null;
            while (true) {
                pack.setLength(BUFSIZE);
                sock.receive(pack);
                String s = new String(
                        pack.getData(),pack.getOffset(),
                        pack.getLength(),"UTF-8");
                String key = (pack.getAddress()+"/") +
                              pack.getPort();
                if (!map.containsKey(key)) {
                    map.put(key,Integer.parseInt(s));
                    s = "Wchodzi " + key;
                } else {
                    s = key + ": " + s;
                }
                resp = s.getBytes("UTF-8");
                rpac = new DatagramPacket(
                    resp,0,resp.length,
                    pack.getAddress(),pack.getPort());
                for (String k : map.keySet()) {
                    rpac.setPort(map.get(k));
                    sock.send(rpac);
                }
            }
        } catch(Exception e) {
            e.printStackTrace(); System.exit(1);
        }
        finally { if (sock != null) sock.close(); }
    }
}
